/**
 * 实时Agent功能测试脚本
 * 直接调用我们实现的Agent函数进行验证
 */

// 导入我们的Agent函数
const { callGameMaster } = require('./dist/mastra/agents/game-master.agent.js');
const { callSuspectDialogue } = require('./dist/mastra/agents/suspect-dialogue.agent.js');
const { analyzeInvestigation } = require('./dist/mastra/agents/investigation.agent.js');
const { evaluateDeduction } = require('./dist/mastra/agents/evaluation.agent.js');

console.log('🚀 开始实时Agent功能验证...\n');

async function testGameMasterAgent() {
  console.log('📋 1. 测试游戏主控Agent...');
  
  try {
    const gameConfig = {
      difficulty: 'normal',
      theme: '办公室',
      suspectCount: 3,
      playerProfile: {
        name: '测试玩家',
        experience: '新手'
      }
    };

    console.log('   🔄 调用游戏主控Agent开始新游戏...');
    const result = await callGameMaster('start_game', {
      gameConfig,
      sessionId: 'test-session-001',
      timestamp: new Date().toISOString()
    });

    if (result.success) {
      console.log('   ✅ 游戏主控Agent测试成功！');
      console.log(`   📊 游戏状态: ${result.gameState?.phase || '未知'}`);
      console.log(`   📝 消息: ${result.message}`);
      return result.data;
    } else {
      console.log('   ❌ 游戏主控Agent测试失败');
      console.log(`   📝 错误: ${result.message}`);
      return null;
    }
  } catch (error) {
    console.log('   ❌ 游戏主控Agent调用异常');
    console.log(`   📝 错误: ${error.message}`);
    return null;
  }
}

async function testSuspectDialogueAgent() {
  console.log('\n📋 2. 测试嫌疑人对话Agent...');
  
  try {
    const suspectData = {
      id: 'suspect-1',
      name: '李秘书',
      personality: '谨慎内向',
      background: '工作认真的秘书',
      alibi: '当时在整理文件',
      suspicionLevel: 4,
      isCulprit: false
    };

    const question = '你当时在哪里？';
    const conversationHistory = [];
    const gameContext = {
      timeRemaining: 180,
      discoveredClues: [],
      suspicionLevel: 5
    };

    console.log('   🔄 调用嫌疑人对话Agent...');
    const result = await callSuspectDialogue(
      suspectData,
      question,
      conversationHistory,
      gameContext
    );

    if (result.success) {
      console.log('   ✅ 嫌疑人对话Agent测试成功！');
      console.log(`   💬 回应: ${result.response}`);
      console.log(`   😊 情绪: ${result.emotion}`);
      console.log(`   🔍 可疑程度: ${result.suspicionLevel}/10`);
      return result;
    } else {
      console.log('   ❌ 嫌疑人对话Agent测试失败');
      console.log(`   📝 错误: ${result.message}`);
      return null;
    }
  } catch (error) {
    console.log('   ❌ 嫌疑人对话Agent调用异常');
    console.log(`   📝 错误: ${error.message}`);
    return null;
  }
}

async function testInvestigationAgent() {
  console.log('\n📋 3. 测试调查分析Agent...');
  
  try {
    const caseData = {
      case: {
        title: '办公室谋杀案',
        description: '在办公室发生了一起神秘的谋杀案',
        location: '办公室',
        timeOfCrime: '上午10:30',
        victim: '张经理'
      },
      suspects: [
        {
          id: 'suspect-1',
          name: '李秘书',
          personality: '谨慎内向',
          suspicionLevel: 4
        }
      ]
    };

    const discoveredClues = [
      {
        id: 'clue-1',
        description: '现场发现的咖啡杯',
        type: 'physical',
        importance: 6
      }
    ];

    const conversationHistory = [
      {
        role: 'detective',
        content: '你当时在哪里？',
        timestamp: new Date().toISOString()
      }
    ];

    console.log('   🔄 调用调查分析Agent...');
    const result = await analyzeInvestigation(
      caseData,
      discoveredClues,
      conversationHistory,
      { timeRemaining: 120 }
    );

    if (result.success) {
      console.log('   ✅ 调查分析Agent测试成功！');
      console.log(`   📊 分析结果: ${result.analysis}`);
      console.log(`   💡 建议数量: ${result.suggestions?.length || 0}`);
      return result;
    } else {
      console.log('   ❌ 调查分析Agent测试失败');
      console.log(`   📝 错误: ${result.message}`);
      return null;
    }
  } catch (error) {
    console.log('   ❌ 调查分析Agent调用异常');
    console.log(`   📝 错误: ${error.message}`);
    return null;
  }
}

async function testEvaluationAgent() {
  console.log('\n📋 4. 测试推理评估Agent...');
  
  try {
    const deductionData = {
      culpritId: 'suspect-1',
      reasoning: '基于对话和线索的综合分析',
      evidence: ['对话内容', '现场线索'],
      confidence: 75
    };

    const caseData = {
      case: {
        title: '办公室谋杀案',
        culpritId: 'suspect-1'
      },
      suspects: [
        {
          id: 'suspect-1',
          name: '李秘书'
        }
      ]
    };

    const gameHistory = {
      discoveredClues: [
        { id: 'clue-1', description: '现场咖啡杯', type: 'physical', importance: 6 }
      ],
      conversationHistory: [
        { role: 'detective', content: '你当时在哪里？' }
      ],
      timeUsed: 180,
      totalTime: 300
    };

    console.log('   🔄 调用推理评估Agent...');
    const result = await evaluateDeduction(
      deductionData,
      caseData,
      gameHistory
    );

    if (result.success) {
      console.log('   ✅ 推理评估Agent测试成功！');
      console.log(`   🎯 推理正确: ${result.isCorrect ? '是' : '否'}`);
      console.log(`   📊 总分: ${result.totalScore}/100`);
      console.log(`   🏆 等级: ${result.grade}`);
      return result;
    } else {
      console.log('   ❌ 推理评估Agent测试失败');
      console.log(`   📝 错误: ${result.message}`);
      return null;
    }
  } catch (error) {
    console.log('   ❌ 推理评估Agent调用异常');
    console.log(`   📝 错误: ${error.message}`);
    return null;
  }
}

async function runAllTests() {
  console.log('🎯 开始完整的Agent功能验证流程...\n');
  
  const results = {
    gameMaster: null,
    suspectDialogue: null,
    investigation: null,
    evaluation: null
  };

  // 测试所有Agent
  results.gameMaster = await testGameMasterAgent();
  results.suspectDialogue = await testSuspectDialogueAgent();
  results.investigation = await testInvestigationAgent();
  results.evaluation = await testEvaluationAgent();

  // 生成测试报告
  console.log('\n' + '='.repeat(60));
  console.log('📊 Agent功能验证报告');
  console.log('='.repeat(60));

  const successCount = Object.values(results).filter(result => result !== null).length;
  const totalTests = Object.keys(results).length;

  console.log(`\n🎯 测试结果: ${successCount}/${totalTests} 通过 (${Math.round(successCount/totalTests*100)}%)`);

  console.log('\n📋 详细结果:');
  console.log(`🤖 游戏主控Agent: ${results.gameMaster ? '✅ 通过' : '❌ 失败'}`);
  console.log(`💬 嫌疑人对话Agent: ${results.suspectDialogue ? '✅ 通过' : '❌ 失败'}`);
  console.log(`🔍 调查分析Agent: ${results.investigation ? '✅ 通过' : '❌ 失败'}`);
  console.log(`📊 推理评估Agent: ${results.evaluation ? '✅ 通过' : '❌ 失败'}`);

  if (successCount === totalTests) {
    console.log('\n🎉 所有Agent功能验证通过！');
    console.log('✅ AI Agent架构改造验证成功！');
  } else {
    console.log('\n⚠️  部分Agent功能需要进一步调试');
  }

  console.log('\n' + '='.repeat(60));
  return results;
}

// 运行测试
runAllTests().catch(error => {
  console.error('❌ 测试运行失败:', error);
  process.exit(1);
});
